package com.fx.springbootdocker;

import cn.hutool.json.JSONUtil;
import com.fx.springbootdocker.dao.ActorFindRepository;
import com.fx.springbootdocker.service.ActorSaveAndDeleteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

@RestController
@RequestMapping("/v1")
@Slf4j
public class TestController {

    @Autowired
    private ActorFindRepository actorFindRepository;

    @Autowired
    private ActorSaveAndDeleteService actorSaveAndDeleteService;

    @GetMapping("/ok")
    public String sayok(){
        return " Are you ok? from="+getLinuxLocalIp();
    }

    @GetMapping("/save")
    public void testSave() {
        Actor actor = actorSaveAndDeleteService.save("高庸涵", 28, "13486627323@163.com");
        log.info(JSONUtil.toJsonPrettyStr(actor));
    }

    @GetMapping("/get")
    public String testFindBySort() {
        Actor actor = actorFindRepository.findByActorNameAndActorEmail("高庸涵", "13486627323@163.com");
        return JSONUtil.toJsonPrettyStr(actor);
    }

    private static String getLinuxLocalIp() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
                                    && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            ip = "127.0.0.1";
            log.error(ex.getMessage(),ex);
        }
        return ip;
    }
}
